package top.jfunc.common.transfer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.jfunc.common.utils.CollectionUtil;

import java.util.List;

/**
 * @author xiongshiyan
 */
public class DataTransferUtil {
	public static final int DEFAULT_BATCH_SIZE = 10000;
	private static final Logger logger = LoggerFactory.getLogger(DataTransferUtil.class);

	private DataTransferUtil(){}

	/**
	 * 通用的批量数据处理方法，提供批次查询和处理的方法即可
	 */
	public static <T> void transferData(String businessName, DataSectionSupplier<T> dss, DataSectionHandler<T> dsh, int batchSize) {
		int pageNumber = 1;
		while (true){
			List<T> recordList = dss.paginate(pageNumber, batchSize);
			logger.info("{} transfer data index {}, size {}, with {}", businessName, pageNumber, batchSize, null != recordList ? recordList.size() : 0);
			if(CollectionUtil.isEmpty(recordList)){
				break;
			}
			dsh.accept(recordList);
			//查询次数小于batchSize，则表示已经查询完毕，下次查询也是返回0没必要浪费一次
			if(recordList.size() < batchSize){
				break;
			}
			pageNumber++;
		}
	}
	public static <T> void transferData(String businessName, DataSectionSupplier<T> dss, DataSectionHandler<T> dsh) {
		transferData(businessName, dss, dsh, DEFAULT_BATCH_SIZE);
	}
}
